/******************************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals settings, Dialog, GroupBox, SpinBox, qsTr*/
/*jslint plusplus: true, indent: 4*/

// Provides resumability for long-running scripts after a crash or user cancel.
//
// Usage:   // Construct the object:
//          var resumable = new Resumable(resumeSettingsKey, 1, files.length, "Import Files"); 
//
//          // Show the dialog:
//          if (!resumable.init())
//                return;
//
//          // Set current progress status:
//	    resumable.setValue(50) 
//
function Resumable(aSettingsKey, aMinValue, aMaxValue, aTitle) {
	"use strict";

	this.minValue = aMinValue;
	this.maxValue = aMaxValue;
	this.currentValue = aMinValue;

	this.settingsKey = aSettingsKey;
	this.dialogTitle = aTitle;
	this.groupBoxTitle = aTitle;
	this.dialogMessage = "";

	// Read value from settings, show dialog, save value to settings. Returns false on cancel press.
	this.init = function () {
		// read values from settings
		this.currentValue = settings.value(this.settingsKey, this.minValue);
		if (this.currentValue < this.minValue) {
			this.currentValue = this.minValue;
		}

		// show the dialog
		var dialog = new Dialog(),
			gbMain = new GroupBox(),
			sbMin = new SpinBox(),
			sbMax = new SpinBox();

		dialog.title = this.dialogTitle;

		gbMain.title = this.groupBoxTitle;
		gbMain.add(this.dialogMessage);
		dialog.add(gbMain);

		sbMin.minimum = this.minValue;
		sbMin.maximum = this.maxValue;
		sbMin.value = this.currentValue;
		gbMain.add(qsTr("From:"), sbMin);

		sbMax.minimum = this.minValue;
		sbMax.maximum = this.maxValue;
		sbMax.value = this.maxValue;
		gbMain.add(qsTr("To:"), sbMax);

		if (!dialog.exec()) {
			return false;
		}

		// save values to settings
		this.minValue = sbMin.value;
		this.maxValue = sbMax.value;
		this.currentValue = sbMin.value;
		settings.setValue(this.settingsKey, this.currentValue);

		return true;
	};

	// Save value to settings
	this.setValue = function (aCurrentValue) {
		this.currentValue = aCurrentValue;
		settings.setValue(this.settingsKey, this.currentValue);
	};
}



